package workers;

import java.beans.PropertyChangeListener;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

import protocol.TransferenciaClienteServidor;
import application.MachineID;
import application.UniqueFileID;

public class ClientListWorker extends TimedWorker implements Runnable {

	List<Object> resultList;
	String patronDeBusqueda;
	String tipoBusqueda;
	MachineID machineID = null;
	public static final String PROPERTY_RESULT_LIST = "resultList";
	
	
	public ClientListWorker(String tipoBusqueda, String patronDeBusqueda , MachineID machineID,PropertyChangeListener changeListener)
	{
		super( "Buscar archivos que cumplan \"" + patronDeBusqueda + "\" en " + machineID.toString() , changeListener);
		this.machineID = machineID;
		resultList = null;
		this.patronDeBusqueda = patronDeBusqueda;
		this.tipoBusqueda = tipoBusqueda;
		setCurrentAction("waiting for turn in poool");

	}
		
	public List<Object> getList(){
		return resultList;
	}
	
	@Override
	public void run() {
		setCurrentAction("running");

		try {

			//open and close the socket to generate a process in the server
			Socket s = machineID.createSocket();
			startWork();		
			assert s.isConnected();
			TransferenciaClienteServidor htc = new TransferenciaClienteServidor();
			String result = htc.pedirListaDeArchivos( s , "Buscar" + tipoBusqueda + patronDeBusqueda +"\n", this);
			
			String parts[] = null;
			parts=result.split("@");
			resultList = new LinkedList<Object>();
			for(int i = 0; i < parts.length; i++){   
				UniqueFileID fileID =  new UniqueFileID(parts[i], machineID.getPeerName(), 1);
				if (tipoBusqueda.equals(Busquedas.BUSCAR_POR_TAMANO))
				{
					String parts1[] = null;
					parts1=result.split("_");					
					fileID =  new UniqueFileID(parts1[0], machineID.getPeerName(), Integer.parseInt(parts1[1].replaceAll("@", "")));
				}				
				resultList.add(fileID);
			}
			propertyChangeSupport.firePropertyChange(PROPERTY_RESULT_LIST, null, resultList);

			s.shutdownInput();
			s.shutdownOutput();
			s.close();
			//setCurrentAction("socket shut down and closed");
			stopWork();
			
			
//		} catch (UnknownHostException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		}catch (Exception e) {
			e.printStackTrace();
			setCurrentAction("failed with " + e.getClass().getCanonicalName());
		}
	}

	@Override
	public void cancelTask() {
		setCanceled(true);
	}
}
